﻿using ClosedXML.Excel;
using Common.Contract;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Service;
using Customer360AutoJob.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using WinSCP;

namespace Customer360AutoJob.Jobs
{
    public class JobBase
    {
        #region Excel


        protected static DataTable ToDataTable<T>(List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                //prop.GetDisplayName(t=>t.name);
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name, prop.PropertyType);
            }
            foreach (T item in items)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }
            //put a breakpoint here and check datatable
            return dataTable;
        }

        protected void ExportToExcel(DataTable dt, string fileName)
        {
            using (XLWorkbook wb = new XLWorkbook())
            {
                var worksheet=  wb.Worksheets.Add(dt, "Sheet1");
                //wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                //wb.Style.Font.Bold = true;

                var firstCell = worksheet.FirstCellUsed();
                var lastCell = worksheet.LastCellUsed();
                var range = worksheet.Range(firstCell.Address, lastCell.Address);
                // We want to use a theme for table, not the hard coded format of the BasicTable
                range.Clear(XLClearOptions.Formats);
                //wb.Theme = XLTableTheme.None;
                var table = worksheet.Tables;
                //worksheet.Tables.Remove(table, convertToRange: true);
                string folderPath = "D:\\ExcelSmartSME\\";
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                wb.SaveAs(folderPath + fileName);
            }

            PutExcelTo8(fileName);
            PutExcelTo9(fileName);

        }

        private void PutExcelTo9(string fileName)
        {
            // Set up session options
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = "10.36.96.9",
                UserName = "sftp_users",
                Password = "Sftp_user123*H",
                SshHostKeyFingerprint = "ssh-rsa 2048 ca:80:ba:3a:55:96:b3:82:84:bd:69:c7:91:e6:99:b5",
            };

            using (Session session = new Session())
            {
                // Connect
                session.Open(sessionOptions);

                // Transfer files
                session.PutFiles(@"D:\ExcelSmartSME\" + fileName, "/smedata/sales_tracking_sme/bic360/*").Check();
            }
        }

        private void PutExcelTo8(string fileName)
        {
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = "10.36.96.8",
                UserName = "sftp_users",
                Password = "Sftp_user123*H",
                SshHostKeyFingerprint = "ssh-rsa 2048 ca:80:ba:3a:55:96:b3:82:84:bd:69:c7:91:e6:99:b5",
            };

            using (Session session = new Session())
            {
                // Connect
                session.Open(sessionOptions);

                // Transfer files
                session.PutFiles(@"D:\ExcelSmartSME\" + fileName, "/smedata/sales_tracking_sme/bic360/*").Check();
            }
        }
        #endregion

        public bool SendEmail(EmailContent content)
        {
            bool isSuccess = true;
            try
            {
                using (var message = new MailMessage("tudd1@vpbank.com.vn", content.To))
                {
                    message.Subject = content.Subject;
                    message.Body = content.Body;
                    if (content.CC != null && content.CC.Count > 0)
                    {
                        content.CC.ForEach(x =>
                        {
                            message.CC.Add(x);
                        });
                    }
                    using (SmtpClient client = new SmtpClient
                    {
                        EnableSsl = true,
                        Host = "smtp.office365.com",
                        Port = 25,
                        Credentials = new NetworkCredential("tudd1@vpbank.com.vn", "Abc@1234")
                    })
                    {
                        client.Send(message);
                        isSuccess = true;
                    }
                }

            }
            catch (Exception)
            {
                isSuccess = false;
            }
            return isSuccess;
        }


        public void UpdateStatusAfterSendEmail(List<RequestCreateDaoRecord> listRequestNeedSendMail)
        {
            using (ServiceClient<IAuthentication> serviceClient = new ServiceClient<IAuthentication>())
            {
                UserRecord CurrentUserRecord = new UserRecord
                {
                    UserName = "cucnt3",
                    GroupIdentifier = "1"
                };
                UpdateCreateDaoRequestRequest requestUpdate = new UpdateCreateDaoRequestRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.DaoManager.ApproveRequestCreateDao"
                    },
                    //Record = userRequest,
                    CurrentUser = CurrentUserRecord,
                    ListCreateDaoRequest = listRequestNeedSendMail
                };
                var result = serviceClient.Proxy.UpdateStatusListRequestDao(requestUpdate);
            }
        }
        public class EmailContent
        {
            public string Subject { get; set; }
            public string Body { get; set; }
            public string To { get; set; }
            public List<string> CC { get; set; }
        }
    }
}